package ms.db.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@EnableTransactionManagement
public class SessionFactory extends LocalSessionFactoryBean {
    @Autowired
    MySqlProperties mySqlProperties;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    MySqlProperties getMysqlProperties() {
        return new MySqlProperties();
    }

    @Bean()
    public DataSource dataSourceFactory() throws Exception {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setAcquireIncrement(mySqlProperties.getAcquireIncrement());
        comboPooledDataSource.setAcquireRetryAttempts(0);
        comboPooledDataSource.setDriverClass(mySqlProperties.getDriverClass());
        comboPooledDataSource.setJdbcUrl(mySqlProperties.getUrl());
        comboPooledDataSource.setAutoCommitOnClose(mySqlProperties.getAutocommit());
        comboPooledDataSource.setMinPoolSize(mySqlProperties.getMinSize());
        comboPooledDataSource.setMaxPoolSize(mySqlProperties.getMaxSize());
        comboPooledDataSource.setUnreturnedConnectionTimeout(mySqlProperties.getTimeout());
        comboPooledDataSource.setIdleConnectionTestPeriod(mySqlProperties.getIdleTestPeriod());
        comboPooledDataSource.setMaxStatements(mySqlProperties.getMaxStatements());
        comboPooledDataSource.setUser(mySqlProperties.getUsername());
        comboPooledDataSource.setPassword(mySqlProperties.getPassword());


        return comboPooledDataSource;
    }


}
